<script setup lang="ts">
/**
 * 根据数据库的字典表,生成select或者radio
 * 使用方法1:<x-dict-select v-model='form.name' type-code='status' />
 */

import {DictSonListType} from "@/api/sys/admin/dict-son/types";
import {getDictOptions} from "@/api/sys/admin/dict";
import {useAttrs} from "vue";

const props = withDefaults(defineProps<
    {
      typeCode: string, // 查询父code得到的儿子列表
      modelValue: string | number | undefined, // 用户v-model的
      type?: 'select' | 'radio' // 是下拉框还是单选框,默认单选框
      disabled?: boolean //
      tag?: boolean // 是否让下拉框颜色变成和tag对应的颜色,默认false,只针对type='select'生效
    }>(), {
  type: 'radio',
  disabled: false,
  tag: true
})

const emits = defineEmits(["update:modelValue",'change']); // 父组件监听事件，同步子组件值的变化给父组件
const options: Ref<DictSonListType[]> = ref([]); // 字典下拉数据源

// 是否为下拉框
const isSelected = computed(() => props.type === 'select')

const {tag} = props

const selectedValue = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emits('update:modelValue', value)
  }
})

function handleChange(val?: string | number) {
  selectedValue.value = val
  emits('change', val)
}

onBeforeMount(async () => {
  // 根据字典类型编码(typeCode)获取字典选项
  options.value = await getDictOptions(props.typeCode)
});
</script>

<template>
  <el-select
      v-if="isSelected"
      v-model="selectedValue"
      :disabled="disabled"
      clearable
      @change="handleChange"
  >
    <el-option
        v-for="option in options"
        :key="option.name + option.code"
        :label="option.name"
        :value="option.code"
    >
      <x-tag v-if="tag" :value="option.code">{{ option.name }}</x-tag>
    </el-option>
  </el-select>
  <el-radio-group v-else v-model="selectedValue" :disabled="disabled" @change="handleChange">
    <el-radio
        v-for="option in options"
        :key="option.name + option.code"
        :label="option.code"
    >
      {{ option.name }}
    </el-radio>
  </el-radio-group>
</template>